package fr.web325.servlet.admin.goods;

import fr.web325.bean.Book;
import fr.web325.dao.BookDao;
import fr.web325.utils.CodeUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

@WebServlet("/shop/modifyBook2")
public class ModifyBook2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Book book = new Book();
        if(req.getParameter("id").equals("")){
            try {
                BeanUtils.populate( book,req.getParameterMap());
                book.setId(new CodeUtils().getId());
                // 新增信息
                if(new BookDao().addBook(book)){
                    req.getRequestDispatcher("/shop/admin/goods").forward(req,resp);
                }
            } catch (IllegalAccessException | InvocationTargetException | SQLException e) {
                e.printStackTrace();
            }
        }else{
            // 修改
            // 获取ID
            try {
                BeanUtils.populate( book,req.getParameterMap());
                // 修改图书信息
                if(new BookDao().editBook(book)){
                    req.getRequestDispatcher("/shop/admin/goods").forward(req,resp);
                }
            } catch (IllegalAccessException | InvocationTargetException | SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
